﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tool.Helper;

namespace DmWordReplaceEx
{
    public partial class WordTemplateBuild : Form
    {
        public WordTemplateBuild()
        {
            InitializeComponent();
            lbl_notice.Text = "";

            this.lbl_notice.BackColor = Color.Transparent;
        }
        bool isRun = false;
        MSWordHelper wordHelper = new MSWordHelper();
        private void btn_start_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbx_excelPath.Text))
            {
                MessageBox.Show("请选择Excel文件", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(tbx_wordPath.Text))
            {
                MessageBox.Show("请选择Word文件", "提示", MessageBoxButtons.OK);
                return;
            }
            ExcelHelperEx excel = new ExcelHelperEx();
            excel.ReadExcelInit(tbx_excelPath.Text);
            var listData = excel.ExcelToArray(1, 1);
            excel.Dispose();
            var maxSize = listData.Count - 2;
            progressBar1.Maximum = maxSize;
            if (isRun)
            {
                return;
            }
            isRun = true;
            Task.Run(() =>
            {
                string replacePrefix = tbx_replacePrefix.Text;
                string replaceSuffix = tbx_replaceSuffix.Text;
                var fileNameArrays = tbx_wordPath.Text.Split('.');
                bool isAllReplace=cbx_AllReplace.Checked;
                var replaceIndexs =new List<int>();   //需要替换的列标
               for(int i = 0; i < listData[0].Count(); i++)
                {
                    if (!string.IsNullOrEmpty(listData[0][i]))
                    { replaceIndexs.Add(i); }
                }
                try
                {
                  
                    //开始替换，从数据行开始
                    for (int i = 2; i < listData.Count; i++)
                    {
                        if (string.IsNullOrEmpty(listData[i][0]))
                        {
                            break;
                        }
                        try
                        {
                            wordHelper.OpenDocument(tbx_wordPath.Text);
                            foreach (var item in replaceIndexs)
                            {
                                var findStr = listData[0][item];
                                var replaceStr = replacePrefix + listData[i][item] + replaceSuffix;
                                do
                                {
                                    if (!isRun || !wordHelper.FindReplace(findStr, replaceStr))
                                    {
                                        break;
                                    }
                                }
                                while (isAllReplace);
                            }
                            string newPath = fileNameArrays[0] + listData[i][0] + "." + fileNameArrays[1];
                            wordHelper.SaveDocument(newPath);
                            this.Invoke(new Action(() =>
                            {
                                progressBar1.Value++;
                                lbl_notice.Text = progressBar1.Value.ToString() + "/" + maxSize;
                            }));
                           
                        }
                        finally
                        {
                            wordHelper.CloseDocument();
                        }
                        if (!isRun)
                        {
                            break;
                        }
                    }
                }
                finally
                {
                    isRun = false;
                }
              
             
                MessageBox.Show("替换完成", "提示", MessageBoxButtons.OK);
            });

        }

        private void btn_dowlloadTemplate_Click(object sender, EventArgs e)
        {
            SaveFileDialog dia = new SaveFileDialog();
            dia.Filter = "工作簿文件（*.xlsx）|*.xlsx|97-2003工作簿文件（*.xls）|*.xls";
            string fielPath;
            if (dia.ShowDialog() == DialogResult.OK)
            {
                fielPath = dia.FileName;
            }
            else
            {
                return;
            }
            ExcelHelperEx excel = new ExcelHelperEx();
            List<string[]> list = new List<string[]>();
            list.Add(new string[8] {"", "[A000]", "[A001]", "[A002]", "[A003]", "[A004]", "[A005]", "[A006]" });
            list.Add(new string[8] { "保存文件后缀", "学号", "姓名", "年龄", "性别", "语文", "数学", "英语" });
            list.Add(new string[8] { "24001_张三", "24001", "张三", "15", "男", "65", "75", "85" });
            list.Add(new string[8] { "24002_李四", "24002", "李四", "15", "女", "66", "76", "86" });
            list.Add(new string[8] { "24003_王二", "24003", "王二", "15", "男", "67", "77", "87" });
            excel.ArrayToExcel(fielPath, list,"批量替换生成");

            excel.CreateSheet("About");
            excel.SetColumnWidth(0, 30000);
            excel.SetValue(0, 0, "1.查找的关键字可以是相同的，也可以是不同的。");
            excel.SetValue(1, 0, "2.当关键字相同时，查找为从文档前面向后查找，一一匹配。");
            excel.SetValue(2, 0, "3.当未查找到关键字时，程序会结束替换，保存为新文档。");
            excel.SetValue(3, 0, "4.当勾选上“全替换”选项时，会将同一关键字全部替换后再替换下一个，仅为关键字不同时使用。");
            excel.SetValue(4, 0, "5.表格第一列为“保存文件后缀”，不可为空。");
            excel.SetValue(5, 0, "6.表格第一行为“关键字”，需要进行替换的列请填上关键字，不需要的替换的清空相应列第一行的关键字。");
            excel.SetValue(6, 0, "7.“保存文件后缀”和“关键字”可以按实际需求进行更改。");
            excel.SetValue(7, 0, "8.本功能使用场景为：有一个Excel统计信息表，有一个 Word模板表，需要把Excel表中的每一行数据填进Word表中，并生成一个新的Word表");

            excel.WorkBookToFileStream(fielPath);
            MessageBox.Show("下载成功", "提示", MessageBoxButtons.OK);
        }

        private void btn_choose_Click(object sender, EventArgs e)
        {
            OpenFileDialog dia = new OpenFileDialog();
            dia.Filter = "工作簿文件（*.xlsx）|*.xlsx|97-2003工作簿文件（*.xls）|*.xls";
            if (dia.ShowDialog() == DialogResult.OK)
            {
                tbx_excelPath.Text = dia.FileName;
            }
        }

        private void btn_stop_Click(object sender, EventArgs e)
        {
            isRun = false;
        }

        private void tbn_wordChoose_Click(object sender, EventArgs e)
        {
            OpenFileDialog dia = new OpenFileDialog();
            dia.Filter = "Word文件（*.docx）|*.docx|97-2003 Word文件（*.doc）|*.doc";
            if (dia.ShowDialog() == DialogResult.OK)
            {
                tbx_wordPath.Text = dia.FileName;
            }
        }

        private void WordTemplateBuild_FormClosing(object sender, FormClosingEventArgs e)
        {
            wordHelper.CloseDocument();
        }
    }
}
